<?php
/* * * * *
 * File: register.php
 * Author: freighter9@gmail.com
 * Version: 0.5 (beta testing)
 *
 * * * * * *
 * License:
 * This file is part of the PLogin project hosted at
 * http://code.google.com/p/plogin.  All files of the PLogin
 * project are licensed under the GNU General Public License 2.0.
 *
 * * * * *
 * Usage:
 * This script handles user account registrations.  It reads post
 * data from register_form.html and logs qualified new accounts
 * into the file passwd.php.
 *
 * * * * *
 */
 
$username = $_POST['username'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$error = null;

// Check for blank fields:
if ($username == null || $username == '')
	$error = $error . 'Error: You must enter a valid username!<br>';
if ($password == null || $password == '')
	$error = $error . 'Error: You must enter a valid password!<br>';
	
// Check for unsupported characters in username:
if (strpbrk($username, "!@ #$%^&*<>?/.,~`=+\|'"))
	$error = $error . 'Error: Username entered contains invalid characters.<br>';

// Check for unmatching passwords:
if (md5($password) != md5($passwordConfirm)) {
	$error = $error . 'Error: Passwords entered did not match.<br>';
}

// Check for repeated username:
$file = "passwd.php";
$fp = fopen($file, 'r');
$fileData = fread($fp, filesize($file));
fclose($fp);

$line = explode("\n", $fileData);

$i = 1;
while ($i <= sizeof($line)) {
	$dataPair = explode(':', $line[$i]);
	if ($dataPair[0] == $username) {
		$error = $error . 'Error: The username "' . $username . '" is already in use.<br>';
	}
	$i++;
}

// Display errors if any:
if ($error) {
	echo $error;
	echo 'Try <a href="register_form.html">registering again</a>.';
	exit;
}

// Add new user to system:
$file = fopen("passwd.php", "a");
$data = $username . ':' . crypt(md5($password), md5($username));
if (fwrite($file, $data . "\n")) {
	echo 'You have been registered successfully.  ';
	echo 'Try <a href="login_form.html">logging in.</a>';
}
else
	echo 'An unknown error occurred.';
fclose($file);
?>